package com.zpark.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zpark.dto.PatientsLoginDto;
import com.zpark.entity.patients.Patients;
import com.zpark.service.PatientsService;
import com.zpark.utils.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/views")
@Api(tags = "患者登录认证")
public class PatientLoginController {

    @Autowired
    private PatientsService patientsService;

    @PostMapping("/login")
    @ApiOperation(value = "患者账号密码登录", notes = "使用账号密码进行登录验证")
    public ResultVO<Patients> login(@Validated @RequestBody PatientsLoginDto dto) {
        // 验证账号密码登录
        Patients patient = patientsService.getOne(new QueryWrapper<Patients>()
            .eq("username", dto.getUsername())
            .eq("role", dto.getRole()));

        if (patient == null) {
            return new ResultVO<>(400, "用户名不存在", null);
        }
        if (!BCrypt.checkpw(dto.getPassword(), patient.getPassword())) {
            return new ResultVO<>(400, "密码错误", null);
        }

        // 设置Spring Security认证信息
        setAuthentication(patient);

        return new ResultVO<>(200, "登录成功", patient);
    }

    // 设置Spring Security认证上下文
    private void setAuthentication(Patients patient) {
        // 构建权限列表
        List<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("ROLE_" + patient.getRole()));

        // 创建认证令牌
        Authentication authentication = new UsernamePasswordAuthenticationToken(
            patient.getPatientsId(), // 使用患者ID作为principal
            null,                   // 凭证设置为null
            authorities             // 用户权限
        );

        // 设置安全上下文
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }
}